/**
 * Created by helly on 15-2-2.
 */
//浏览器版本
var browser = {};
var ua = navigator.userAgent.toLowerCase();
var browserStr;
(browserStr = ua.match(/msie ([\d]+)/)) ? browser.ie = browserStr[1] :
    (browserStr = ua.match(/firefox\/([\d]+)/)) ? browser.firefox = browserStr[1] :
        (browserStr = ua.match(/chrome\/([\d]+)/)) ? browser.chrome = browserStr[1] :
            (browserStr = ua.match(/opera.([\d]+)/)) ? browser.opera = browserStr[1] :
                (browserStr = ua.match(/version\/([\d]+).*safari/)) ? browser.safari = browserStr[1] : 0;
var isPad = navigator.userAgent.match(/iPad|iPhone|iPod|Android/i) != null;
//isPad = true;
//Prevent memory leaks in IE6
if (browser.ie == 6) {
    window.attachEvent("onunload", function () {
        for (var id in jQuery.cache) {
            if (jQuery.cache[id].handle) {
                try {
                    jQuery.event.remove(jQuery.cache[id].handle.elem);
                } catch (e) {}
            }
        }
    });
}


//tip消息提示
(function ($) {
    jQuery.tipMessage = function (msg, type, time, zIndex, callback) {
        if (typeof tipMessageTimeoutId !== 'number') {
            tipMessageTimeoutId = 0
        }
        if (typeof time !== 'number') {
            time = 2000
        }
        if (typeof zIndex !== 'number' || zIndex == 0) {
            zIndex = 65500
        }
        var $doc = $(document);
        var $win = $(window);
        var $tipMessage = $('#tipMessage');
        var _typeTag = '';
        var _newTop = 0;
        var _newLeft = 0;
        var _width = 0;
        var _NumCount = 1;
        var _mask = "";

        if ($tipMessage.length <= 0) {
            $("body").append('<div id="tipMessage" class="tip_message" ></div>');
            $tipMessage = $('#tipMessage');
        } else {
            if (browser.ie == 6 || browser.ie == 7) {
                $tipMessage.css({
                    width: '99%'
                });
            } else {
                $tipMessage.css({
                    width: 'auto'
                });
            }
        }
        $tipMessage.css({
            opacity: 0,
            zIndex: zIndex
        });
        clearTimeout(tipMessageTimeoutId); //清除旧的延时事件

        if (type == 1) {
            _typeTag = 'hits';
        } else if (type == 2) {
            _typeTag = 'fail';
        } else {
            _typeTag = 'succ';
        }
        if (browser.ie == 6) {
            _mask = '<iframe frameborder="0" scrolling="no" class="ie6_mask"></iframe>';
        }
        $tipMessage.html(_mask + '<div class="tip_message_content"><span class="tip_ico_' + _typeTag + '"></span><span class="tip_content" id="tip_content">' + msg + '</span><span class="tip_end"></span></div>').show();


        //计算top,left 值

        function _calculate() {
            _width = $('#tip_content').width() + 86; //计算tip宽度
            if ($doc.scrollTop() + $win.height() > $doc.height()) {
                _newTop = $doc.height() - $win.height() / 2 - 40;
            } else {
                _newTop = $doc.scrollTop() + $win.height() / 2 - 40;
            }

            if ($win.width() >= $doc.width()) {
                _newLeft = $doc.width() / 2 - _width / 2;
            } else {
                if ($win.width() <= _width) {
                    if ($doc.scrollLeft() + $win.width() + (_width - $win.width()) / 2 > $doc.width()) {
                        _newLeft = $doc.width() - _width;
                    } else {
                        _newLeft = $doc.scrollLeft() + $win.width() / 2 - _width / 2;
                    }
                } else {
                    //alert(1);
                    _newLeft = $doc.scrollLeft() + $win.width() / 2 - _width / 2;

                }
            }
            if (_newLeft < 0) {
                _newLeft = 0;
            }
        }
        _calculate(); //计算top,left 值
        $tipMessage.css({
            top: _newTop,
            left: _newLeft,
            width: _width,
            opacity: 10
        });

        //重置

        function _reSet() {
            _calculate(); //从新计算top,left 值
            $tipMessage.css({
                top: _newTop,
                left: _newLeft,
                width: _width
            });
        }
        //调整大小

        function _resize() {
            if (_NumCount % 2 == 0) { //解决IE6下scrollLeft值问题
                _reSet();
                _NumCount = 1;
            } else {
                ++_NumCount;
            }
        }
        if (!isPad) { //pad设备不支持浮动
            $win.bind({
                "scroll": _reSet,
                "resize": _resize
            });
        }
        tipMessageTimeoutId = setTimeout(function () {
            $tipMessage.remove();
            if (typeof callback == 'function') {
                callback.call();
            }
        }, time);
    };
})(jQuery);


//DIV输入框高度自动调整插件，专处理IE6版
(function(jQuery) {
    jQuery.fn.extend({
        elastic: function(options) {
            var defaults = {
                maxHeight: 1024
            };
            var options = $.extend(defaults, options);
            var mimics = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontSize', 'lineHeight', 'fontFamily', 'width', 'fontWeight'];
            return this.each(function() {
                var $obj = $(this),
                    maxheight = parseInt(options.maxHeight, 10) || Number.MAX_VALUE,
                    minheight = parseInt($obj.css('height'), 10) || lineHeight * 3,
                    $twin = jQuery('<div />').css({
                        'position': 'absolute',
                        'display': 'none',
                        'word-wrap': 'break-word',
                        'word-break': 'break-all'
                    });
                $twin.appendTo($obj.parent());
                var i = mimics.length;
                while (i--) {
                    $twin.css(mimics[i].toString(), $obj.css(mimics[i].toString()));
                }

                function update() {
                    var tContent = $obj.html()
                    var twinContent = $twin.html();
                    if (tContent != twinContent) {
                        $twin.html(tContent);
                        if (Math.abs($twin.height() - $obj.height()) > 3) {
                            var goalheight = $twin.height();
                            if (goalheight >= maxheight) {
                                $obj.css({'height': maxheight + 'px', 'overflow-y': 'auto'});
                            }
                            else if (goalheight <= minheight) {
                                $obj.css({'height': minheight + 'px', 'overflow-y': 'hidden'});
                            }
                            else {
                                $obj.css({'height': goalheight + 'px', 'overflow-y': 'hidden'});
                            }
                        }
                    }
                }
                if (browser.ie==6 && !$.support.style) {
                    $obj.css({'overflow-y': 'hidden'});
                    $obj.keyup(function() {
                        update();
                    });
                }
            })
        }
    })
})(jQuery);



//用户
var user={

    register: function(){
        var $uname = $("#uname");
        var $nickname = $("#nickname");
        var $password = $("#password");
        var $password2 = $("#password2");
        var $vCode = $('#vCode');
        var $errmsg = $('.errmsg');

        $("#regSubmit").click(function () {
            if ($uname.val().length<3) {
                $errmsg.html('请输入正确的账号！').show();
                $uname.val('').focus();
                return false;
            }  else if ($nickname.val().length < 3) {
                $errmsg.html('请输入昵称,昵称为3个字符以上！').show();
                $nickname.focus();
                return false;
            }  else if ($password.val().length < 6) {
                $errmsg.html('密码长度应大于6位！').show();
                $password.focus();
                return false;
            } else if ($password.val() != $password2.val()) {
                $errmsg.html('两次输入的密码不一致！').show();
                $password.focus();
                return false;
            } else if ($vCode.val().length !== 4) {
                $errmsg.html('请输入4位验证码。').show();
                $vCode.focus();
                return false;
            }
            $errmsg.html("注册中，请稍后...").show();
			
            $.ajax({
                type: "POST",
                global: false, // 禁用全局Ajax事件.
                url: GM.siteUrl + "index.php?m=User&c=Login&a=doRegister",
                data: {
                    uname: $uname.val(),
                    nickname: $nickname.val(),
                    password: $password.val(),
                    password2: $password2.val(),
                    vCode: $vCode.val()
                },
                dataType: "json",
                success: function (data) {
                    if(data.status){
                        $errmsg.html(data.info);
                        if (data.url) {
                            setTimeout(function(){
                                location.href=data.url;
                            },2000);
                        } else {
                            setTimeout(function(){
                                libs.reloadPage(window);
                            },2000);
                        }
                    }else{
                        $errmsg.html(data.info);
                        libs.changeAuthCode();
                        return false;
                    }
                },
                error: function () {
                    alert("数据执行错误！");
                    return false;
                }

            });



        })

    },

    /**
     *第三方登录
     */
    thirdReg: function(){
        var $uname = $("#uname");
        var $nickname = $("#nickname");
        var $password = $("#password");
        var $password2 = $("#password2");
        var $type = $("#type");
        var $uavatar = $("#uavatar");
        var $openkey = $("#openkey");
        var $errmsg = $('.errmsg');

        $("#thirdReg").click(function () {
            if ($uname.val().length<3) {
                $errmsg.html('请输入正确的账号！').show();
                $uname.val('').focus();
                return false;
            }  else if ($nickname.val().length < 3) {
                $errmsg.html('请输入昵称,昵称为3个字符以上！').show();
                $nickname.focus();
                return false;
            }  else if ($password.val().length < 6) {
                $errmsg.html('密码长度应大于6位！').show();
                $password.focus();
                return false;
            }else if ($password.val() != $password2.val()) {
                $errmsg.html('两次输入的密码不一致！').show();
                $password.focus();
                return false;
            } 
            $errmsg.html("授权登录中，请稍候...").show();

            $.ajax({
                type: "POST",
                global: false, // 禁用全局Ajax事件.
                url: GM.siteUrl + "index.php?m=User&c=Login&a=thirdReg",
                data: {
                    uname: $uname.val(),
                    nickname: $nickname.val(),
                    password: $password.val(),
                    password2: $password2.val(),
                    type: $type.val(),
                    uavatar: $uavatar.val(),
                    openkey: $openkey .val()
                },
                dataType: "json",
                success: function (data) {
                    if(data.status){
                        $errmsg.html(data.info);
                        if (data.url) {
                            setTimeout(function(){
                                location.href=data.url;
                            },2000);
                        } else {
                            setTimeout(function(){
                                libs.reloadPage(window);
                            },2000);
                        }
                    }else{
                        $errmsg.html(data.info);
                        libs.changeAuthCode();
                        return false;
                    }
                },
                error: function () {
                    alert("数据执行错误！");
                    return false;
                }
            });
        })

    },

    //会员登录
    login: function () {
        var $backurl = $("#backurl").val();
        var $uname = $("#uname");
        var $password = $("#password");
        var $autoLogin = $('#autoLogin');
        var $errmsg = $('.errmsg');
        $("#loginSubmit").live('click',function () {
            if ($uname.val().length<3) {
                $errmsg.html('请输入正确的账号！').show();
                $uname.val('').focus();
                return false;
            }  else if ($password.val().length < 6) {
                $errmsg.html('密码长度应大于6位！').show();
                $password.focus();
                return false;
            }

            if ($autoLogin.checked==true) {
                $autoLogin = 1;
            } else {
                $autoLogin = 0;
            }
            $errmsg.html("登录中，请稍后...").show();

            $.getJSON(GM.siteUrl + "index.php?m=User&c=Login&a=dologin", "username=" + escape($uname.val()) + "&password=" + escape($password.val()) + "&autoLogin=" + escape($autoLogin) + '&escape=1',
                function (data) {
                    if(data.status){
                        $errmsg.html(data.info);

                        if ($backurl != undefined && $backurl != '') {
                            location.href = $backurl;
                        } else {
                            location.href = data.url;
                        }

                    }else{
                        $errmsg.html(data.info);
                        return false;
                    }

                });
            return false;
        });
    }

}



//公共类
var libs = {

    allSelect: function (objName) { //全选
        $('#' + objName + ' :checkbox').each(function () {
            if (!$(this).attr('disabled')) {
                $(this).attr('checked', 'checked');
            }
        });
    },
    otherSelect: function (objName) { //反选
        $('#' + objName + ' :checkbox').each(function () {
            if ($(this).attr('checked')) {
                $(this).removeAttr('checked');
            } else {

                if (!$(this).attr('disabled')) {
                    $(this).attr('checked', 'checked');
                }
            }
        });
    },

    //验证码
    changeAuthCode: function () {
        var num = new Date().getTime();
        var rand = Math.round(Math.random() * 10000);
        var num = num + rand;
        $("#authCode").attr('src', $("#authCode").attr('src') + "&t=" + num);
    },
    redirect: function (url) {
        location.href = url;
    },
    imageError: function (obj) {
        obj.onerror = null;
        obj.src = _config['domainStatic'] + "/static/home/images/none.gif";
    },

    //重新刷新页面，使用location.reload()有可能导致重新提交
    reloadPage: function(win) {
    var location = win.location;
    location.href = location.pathname + location.search;
    },


//验证码

    vcodeRefresh: function(){
        $("#authCode").click(function () {
            libs.changeAuthCode();
            return false;
        });

        $('#changeAuthCode').click(function () {
            libs.changeAuthCode();
            return false;
        });
    },





};
